package com.cjgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjgl.common.BaseResponse;
import com.cjgl.common.ErrorCode;
import com.cjgl.common.ResultUtils;
import com.cjgl.exception.BusinessException;
import com.cjgl.model.dto.score.SelectScoresByTermOrCourseNameREquest;
import com.cjgl.model.dto.teacher.GetStudentScoresRequest;
import com.cjgl.model.dto.teacher.GetTeacherInfoRequest;
import com.cjgl.model.dto.teacher.TeacherRequestInsertScores;
import com.cjgl.model.entity.Coursestableview;
import com.cjgl.model.entity.Scoresstudentview;
import com.cjgl.model.entity.TblScores;
import com.cjgl.model.entity.TblTeacher;
import com.cjgl.model.enums.LengthTypeEnum;
import com.cjgl.model.vo.courseTable.CourseNoAndCourseNameVo;
import com.cjgl.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

import static com.cjgl.constant.UserConstant.USER_LOGIN_STATE;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: M
 * @Date: 2023/05/29/13:27
 * @Description:
 */


@RestController
@RequestMapping("/teacher")
public class TeacherController {

	@Resource
	TblCoursestableService tblCoursestableService;
	@Resource
	TblScoresService tblScoresService;
	@Resource
	TblStudentsService tblStudentsService;
	@Resource
	TblCoursesService tblCoursesService;

	@Resource
	TblTeacherService teacherService;

	@Resource
	ScoresstudentviewService scoresstudentviewService;

	@Resource
	CoursestableviewService coursestableviewService;

	/**
	 * 获取全部老师信息
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/getAllTeacher")
	public BaseResponse<Object> getAllTeachers( HttpServletRequest request) {
		TblTeacher teacher = (TblTeacher)request.getSession().getAttribute(USER_LOGIN_STATE);
		LambdaQueryWrapper<TblTeacher> teacherQueryWrapper = new LambdaQueryWrapper<>();
		teacherQueryWrapper.eq(TblTeacher::getTeacherDeptname, teacher.getTeacherDeptname());
		List<TblTeacher> teachers = teacherService.getBaseMapper().selectList(teacherQueryWrapper);
		return ResultUtils.success(teachers);
	}

	/**
	 *   查询自己的课程表信息 year ter teacherNo
	 * <p>
	 * 作控制选年可以选学期(反之不行)
	 * 补充：最好设定学年和学期数
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/get/curriculum")
	public BaseResponse<List<Coursestableview>> getTeacherCurriculum(@RequestBody SelectScoresByTermOrCourseNameREquest term, HttpServletRequest request) {
		TblTeacher attribute = (TblTeacher) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (attribute == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		Calendar calendar = Calendar.getInstance();

		String year = term.getYear() != null ? term.getYear() : calendar.get(Calendar.YEAR) + "";
		String ter = term.getTer() != null ? term.getTer() : calendar.get(Calendar.MONTH) <= 8 ? 2 + "" : 1 + "";
		if (ter.length() == 1) {
			ter = "0" + ter;
		}
		if (term.getYear() != null && term.getTer() == null) {
			ter = "";
		}
		String termSelect = "";

		termSelect = year + ter;
		String teacherNo = attribute.getTeacherNo();
		if (StringUtils.isBlank(teacherNo)) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		LambdaQueryWrapper<Coursestableview> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper
				.eq(Coursestableview::getTeacherNo, teacherNo)
				.like(!StringUtils.isEmpty(termSelect), Coursestableview::getTerm, termSelect);


		List<Coursestableview> coursestableviews = coursestableviewService.getBaseMapper().selectList(queryWrapper);
		return ResultUtils.success(coursestableviews);
	}


	/**
	 * 先根据teacherNo
	 * 根据  课程号   课程号  班级号 获取这个老师交的所有的课程
	 *
	 * @param getCondition
	 * @return
	 */
	@PostMapping("/getTeachCourseNoAndName")
	public BaseResponse<List<CourseNoAndCourseNameVo>> getTeachCourseNoAndName(GetStudentScoresRequest getCondition, HttpServletRequest request) {
		TblTeacher attribute = (TblTeacher) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (attribute == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		Calendar calendar = Calendar.getInstance();

		String year = getCondition.getYear() != null ? getCondition.getYear() : calendar.get(Calendar.YEAR) + "";
		String ter = getCondition.getTer() != null ? getCondition.getTer() : calendar.get(Calendar.MONTH) <= 8 ? 2 + "" : 1 + "";
		if (ter.length() == 1) {
			ter = "0" + ter;
		}
		if (getCondition.getYear() != null && getCondition.getTer() == null) {
			ter = "";
		}
		String termSelect = "";

		termSelect = year + ter;

		LambdaQueryWrapper<Coursestableview> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.select(Coursestableview::getCourseNo,Coursestableview::getCourseName,Coursestableview::getClassNo)
				.eq(Coursestableview::getTeacherNo, attribute.getTeacherNo())
				.like(!StringUtils.isEmpty(termSelect), Coursestableview::getTerm, termSelect);


		List<Coursestableview> courseNoNameAndClassNos = coursestableviewService.getBaseMapper().selectList(queryWrapper);

		List<CourseNoAndCourseNameVo> courseNoAndCourseNameVoList = courseNoNameAndClassNos.stream().map(item -> {
			CourseNoAndCourseNameVo courseNoAndCourseNameVo = new CourseNoAndCourseNameVo();
			courseNoAndCourseNameVo.setCourseNo(item.getCourseNo());
			courseNoAndCourseNameVo.setCourseName(item.getCourseName());
			courseNoAndCourseNameVo.setClassNo(item.getClassNo());
			return courseNoAndCourseNameVo;
		}).collect(Collectors.toList());
		return ResultUtils.success(courseNoAndCourseNameVoList);
	}


	/**
	 * 根据课程号 班级号 课程名 模糊查询自己交过的所有学生返回信息包含成绩
	 * @param getCondition
	 * @param request
	 * @return
	 */
	@PostMapping("/getScoresInfo")
	public BaseResponse<List<Scoresstudentview>> getScoresInfo(@RequestBody CourseNoAndCourseNameVo getCondition, HttpServletRequest request) {
		TblTeacher attribute = (TblTeacher) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (attribute == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		LambdaQueryWrapper<Scoresstudentview> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper
				.like(!StringUtils.isEmpty(getCondition.getCourseNo()),Scoresstudentview::getCourseNo,getCondition.getCourseNo())
				.like(!StringUtils.isEmpty(getCondition.getCourseName()),Scoresstudentview::getCourseName,getCondition.getCourseName())
				.like(!StringUtils.isEmpty(getCondition.getClassNo()),Scoresstudentview::getStudentClassNo,getCondition.getClassNo());

		List<Scoresstudentview> scoresstudentviews = scoresstudentviewService.getBaseMapper().selectList(queryWrapper);

		return ResultUtils.success(scoresstudentviews);
	}

	/**
	 * 查询所授课程的学生成绩（实现了按 学期 学生姓名 学号 课程号 课程名的模糊查询匹配）
	 *
	 * @param selectCondition
	 * @return
	 */
	@GetMapping("/get/Scores")
	public BaseResponse<List<Scoresstudentview>> getScoresList(SelectScoresByTermOrCourseNameREquest selectCondition) {
		String termSelect = "";
		String year = selectCondition.getYear() != null ? selectCondition.getYear() : "";
		String ter = selectCondition.getTer() != null ? selectCondition.getTer() : "";
		String studentNameSelect = selectCondition.getStudentName() != null ? selectCondition.getStudentName() : "";
		String studentNoSelect = selectCondition.getStudentNo() != null ? selectCondition.getStudentNo() : "";
		String courseNo = selectCondition.getCourseNo() != null ? selectCondition.getCourseNo() : "";
		String courseName = selectCondition.getCourseName() != null ? selectCondition.getCourseName() : "";

		termSelect = year + ter;

		LambdaQueryWrapper<Scoresstudentview> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper
				.like(!StringUtils.isEmpty(termSelect), Scoresstudentview::getTerm, termSelect)
				.like(!StringUtils.isEmpty(studentNameSelect), Scoresstudentview::getStudentName, studentNameSelect)
				.like(!StringUtils.isEmpty(studentNoSelect), Scoresstudentview::getStudentNo, studentNoSelect)
				.like(!StringUtils.isEmpty(courseNo), Scoresstudentview::getCourseNo, courseNo)
				.like(!StringUtils.isEmpty(courseName), Scoresstudentview::getCourseName, courseName);

		List<Scoresstudentview> scoresstudentviewList = scoresstudentviewService.getBaseMapper().selectList(queryWrapper);

		return ResultUtils.success(scoresstudentviewList);
	}

	/**
	 * 模糊查询所授课程信息 完成根据 term courseName courseNo accurateToDay(最多可以精确到天的授课时间 由year month day拼接而成  例如 2022 5 31
	 * 可以都不选 day选了year必须选   day选了year和month必须选)
	 * fanh
	 *
	 * @param request
	 * @return 返回  Coursestableview
	 */
	@GetMapping("/get/sources")
	public BaseResponse<List<Coursestableview>> getTeacherCourses(SelectScoresByTermOrCourseNameREquest coursesSelectCon, HttpServletRequest request) {
		TblTeacher attribute = (TblTeacher) request.getSession().getAttribute(USER_LOGIN_STATE);
		if (attribute == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}

		String teacherNo = attribute.getTeacherNo();
		if (StringUtils.isBlank(teacherNo)) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		String courseNo = coursesSelectCon.getCourseNo() == null ? "" : coursesSelectCon.getCourseNo();
		String courseName = coursesSelectCon.getCourseName() == null ? "" : coursesSelectCon.getCourseName();
//		String authTime = coursesSelectCon.getAuthTime() == null ? "" : coursesSelectCon.getAuthTime();

		String ter = coursesSelectCon.getTer() == null ? "" : coursesSelectCon.getTer();
		//year默认4位长度
		String year = coursesSelectCon.getYear() == null ? "" : coursesSelectCon.getYear();
		String courseTeachingYear = coursesSelectCon.getCourseTeachingYear() == null ? "" : coursesSelectCon.getCourseTeachingYear();
		String month = coursesSelectCon.getMonth() == null ? "" : coursesSelectCon.getMonth();
		String day = coursesSelectCon.getDay() == null ? "" : coursesSelectCon.getDay();

		if (month.length() != LengthTypeEnum.MONTH_LENGTH.getValue() && month.length() == 1) {
			month = "-0" + month;
		}
		if (day.length() != LengthTypeEnum.DAY_LENGTH.getValue() && month.length() == 1) {
			day = "-0" + day;
		} else if (day.length() == LengthTypeEnum.DAY_LENGTH.getValue()) {
			day = "-" + day;
		}

		String accurateToDay = courseTeachingYear + month + day;
		String termSelect = year + ter;


		LambdaQueryWrapper<Coursestableview> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper
				.like(!StringUtils.isEmpty(courseNo), Coursestableview::getCourseNo, courseNo)
				.like(!StringUtils.isEmpty(courseName), Coursestableview::getCourseName, courseName)
				.like(!StringUtils.isEmpty(termSelect), Coursestableview::getTerm, termSelect)
				.like(!StringUtils.isEmpty(accurateToDay), Coursestableview::getTeachingTime, accurateToDay);

		List<Coursestableview> coursestableviewList = coursestableviewService.getBaseMapper().selectList(queryWrapper);


//		List<TblCoursestable> teacherNo1 = tblCoursestableService.list(new QueryWrapper<TblCoursestable>().eq("teacherNo", teacherNo));
		return ResultUtils.success(coursestableviewList);
	}

	/**
	 * todo 录入成绩（用excel上传） 后面改
	 * 录入学生成绩信息
	 *
	 * @param teacherRequestInsertScores
	 * @return
	 */
	@PostMapping("/saveScores")
	public BaseResponse<Boolean> saveScores(@RequestBody TeacherRequestInsertScores teacherRequestInsertScores) {
		if (teacherRequestInsertScores == null) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

			TblScores tblScores = new TblScores();
			BeanUtils.copyProperties(teacherRequestInsertScores, tblScores);

		boolean result = tblScoresService.update(tblScores, new QueryWrapper<TblScores>()
				.eq("courseNo", tblScores.getCourseNo()).eq("studentNo", tblScores.getStudentNo()));
		return ResultUtils.success(result);
	}
}
